﻿using AspNetMVCTodo.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;

namespace AspNetMVCTodo.Controllers
{
    [Authorize(Roles = "Administrator")]       // 仅对管理员角色开放此控制器
    public class ManageUsersController(UserManager<ApplicationUser> userManager) : Controller
    {
        private readonly UserManager<ApplicationUser> _userManager = userManager;

        public async Task<IActionResult> Index()
        {
            var admins = (await _userManager.GetUsersInRoleAsync("Administrator")).ToArray();

            var everyone = await _userManager.Users.ToArrayAsync();

            var model = new ManageUsersViewModel
            {
                Administrators = admins,
                Everyone = everyone
            };

            return View(model);
        }

        public async Task<IActionResult> DeleteUser(string userId)
        {
            // 删除用户的逻辑将在这里实现
            if (string.IsNullOrWhiteSpace(userId))
            {
                return View("User Id Error");
            }
            ;

            //根据 Id 查询用户
            var user = await _userManager.FindByIdAsync(userId);
            if (user == null)
            {
                return NotFound();
            }

            var currentUser = await _userManager.GetUserAsync(User);
            if (user.Id == currentUser?.Id)
            {
                // 防止管理员删除自己
                return BadRequest("You cannot delete your own account.");
            }

            user.IsDeleted = true;
            user.DeletedAt = DateTime.UtcNow;
            user.DeletedBy = currentUser?.UserName;

            var result = await _userManager.UpdateAsync(user);
            if (result.Succeeded)
            {
                TempData["SuccessMessage"] = "用户删除成功";
            }
            else
            {
                TempData["ErrorMessage"] = "用户删除失败";
            }
            return RedirectToAction("Index");
        }
    }
}
